package com.yakaten.service;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.text.DecimalFormat;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.commons.io.IOUtils;
import org.seasar.framework.util.ResourceUtil;

import com.yakaten.dto.KakakuItemInfoDto;
import com.yakaten.exception.KakakuException;
import com.yakaten.login.KakakuLogin;
import org.seasar.framework.log.Logger;

public class KakakuItemService {

	static Logger logger = Logger.getLogger(KakakuItemService.class);

	protected static final String REGEX_SHOP_DETAIL = "<div class=\"shopDetailTop\">(.*?)</div>";

//	protected static final String REGEX_ITEMNAME = "<div id=\"titleBox\"><h2>(.*)</h2>";
	protected static final String REGEX_ITEMNAME = "<h1 class=\"hType0\">(.*)</h1>";

//	protected static final String REGEX_ITEMPRICE = "<p class=\"fontPrice wordwrapPrice\">&yen;(.*?)</p>";
	protected static final String REGEX_ITEMPRICE = "<dd class=\"price\">&yen;(.*?)<span";

	// protected static final String REGEX_INFO =
	// "<tr>.*(<td.*>.*</td>).*</tr>";
	// protected static final Pattern PATTERN_INFO = Pattern.compile(REGEX_INFO,
	// Pattern.MULTILINE);

//	protected static final String REGEX_SHOPNAME = "<td class=\"shopnameL\"><p class=\"wordwrapShop\"><a.*?>(.*?)</a>";
	protected static final String REGEX_SHOPNAME = "<dt class=\"shopName\"><p class=\"txt\"><a href=\".*?\">(.*?)</a>";

	protected static final String REGEX_SYORYU = "<dd class=\"stoc\"><ul><li>送料&yen;(.*?)</li>";

	protected static final String REGEX_SYORYU_A = "送料&yen;(.*?)";


	protected static final Pattern PATTERN_SHOP_DETAIL = Pattern.compile(
			REGEX_SHOP_DETAIL, Pattern.MULTILINE);

	protected static final Pattern PATTERN_SHOPNAME = Pattern.compile(
			REGEX_SHOPNAME, Pattern.MULTILINE);
	protected static final Pattern PATTERN_SYORYU = Pattern.compile(
			REGEX_SYORYU, Pattern.MULTILINE);
	protected static final Pattern PATTERN_SYORYU_A = Pattern.compile(
			REGEX_SYORYU_A, Pattern.MULTILINE);

	protected static final Pattern PATTERN_ITEMNAME = Pattern.compile(
			REGEX_ITEMNAME, Pattern.MULTILINE);
	protected static final Pattern PATTERN_ITEMPRICE = Pattern.compile(
			REGEX_ITEMPRICE, Pattern.MULTILINE);
	private static final String REGEX_HOTTID = "<input type=\"hidden\" name=\"hottid\" value=\"(.+?)\">";
	private static final Pattern PATTERN_HOTTID = Pattern.compile(REGEX_HOTTID);
	protected static final DecimalFormat PRICE_FORMAT = new DecimalFormat(
			"###,###.###");

	public List<KakakuItemInfoDto> getItemInfo(String itemId)
			throws KakakuException {
		List<KakakuItemInfoDto> resultList = new ArrayList<KakakuItemInfoDto>();

//		String KAKAKU_HOST = ResourceUtil.getProperties("yakaten.properties")
//				.getProperty("kakaku.host");

		String KAKAKU_HOST = "http://s.kakaku.com/";
		String url = KAKAKU_HOST + "item/" + itemId;



		BufferedReader bufferedReader = null;
		HttpURLConnection connection = null;
		try {
			URL loginUrl = new URL(url);
			connection = (HttpURLConnection) loginUrl.openConnection();
			connection
			.setRequestProperty(
					"User-Agent",
					"Mozilla/5.0 (iPhone; CPU iPhone OS 5_0 like Mac OS X) AppleWebKit/534.46 (KHTML, like Gecko) Version/5.1 Mobile/9A334 Safari/7534.48.3");
			connection.connect();

			InputStream urlStream = connection.getInputStream();
			bufferedReader = new BufferedReader(new InputStreamReader(
					urlStream, "shift_jis"));
			String ss = null;
			StringBuffer htmlBuffer = new StringBuffer();
			while ((ss = bufferedReader.readLine()) != null) {
				htmlBuffer.append(ss);
			}

			if (htmlBuffer != null) {

				Matcher matcherItemName = PATTERN_ITEMNAME.matcher(htmlBuffer);
				String itemName ="";
				if (matcherItemName.find()) {
					itemName =matcherItemName.group(1);
					itemName = itemName.replace("&#215;", "×");
				}

				Matcher matcherShopDetail = PATTERN_SHOP_DETAIL
						.matcher(htmlBuffer);
				while (matcherShopDetail.find()) {
					String shopDetail =matcherShopDetail.group(1);
					KakakuItemInfoDto kakakuItemInfo = new KakakuItemInfoDto();

					//price
					Matcher matcherItemPrice = PATTERN_ITEMPRICE
							.matcher(shopDetail);
					if (matcherItemPrice.find()) {
						kakakuItemInfo.setItemPrice(PRICE_FORMAT.parse(matcherItemPrice.group(1))
								.longValue());
					}

					//shopname
					Matcher matcherShopName = PATTERN_SHOPNAME.matcher(shopDetail);
					if (matcherShopName.find()) {
						kakakuItemInfo.setShopName(matcherShopName.group(1).trim());
					}

					//syoryu
					Matcher matcherSyoryu = PATTERN_SYORYU.matcher(shopDetail);
					if (matcherSyoryu.find()) {
						String syoryuString = matcherSyoryu.group(1).trim();
						if(syoryuString!=null && syoryuString.indexOf("〜")>0){
							syoryuString = syoryuString.replaceAll("〜", "");
						}
						if(syoryuString !=null && !syoryuString.equals(""))
						kakakuItemInfo.setSyoryu(PRICE_FORMAT.parse(syoryuString)
								.longValue());

					}

					kakakuItemInfo.setItemName(itemName);
					kakakuItemInfo.setItemUrl(url);
					kakakuItemInfo.setItemId(itemId);
					resultList.add(kakakuItemInfo);
				}

//
//				Matcher matcherItemPrice = PATTERN_ITEMPRICE
//						.matcher(htmlBuffer);
//				List<String> itemPriceList = new ArrayList<String>();
//				while (matcherItemPrice.find()) {
//					itemPriceList.add(matcherItemPrice.group(1));
//				}
//
//				Matcher matcherShopName = PATTERN_SHOPNAME.matcher(htmlBuffer);
//				List<String> itemShopNameList = new ArrayList<String>();
//				while (matcherShopName.find()) {
//					itemShopNameList.add(matcherShopName.group(1));
//				}
//
//				Matcher matcherItemName = PATTERN_ITEMNAME.matcher(htmlBuffer);
//				String itemName ="";
//				if (matcherItemName.find()) {
//					itemName =matcherItemName.group(1);
//					itemName = itemName.replace("&#215;", "×");
//				}
//
//				for(int i=0;i<itemPriceList.size();i++){
//					KakakuItemInfoDto kakakuItemInfo = new KakakuItemInfoDto();
//					kakakuItemInfo.setItemId(itemId);
//					kakakuItemInfo.setItemName(itemName);
//					kakakuItemInfo.setItemUrl(url);
//					kakakuItemInfo.setItemPrice(PRICE_FORMAT.parse(itemPriceList.get(i))
//							.longValue());
//					kakakuItemInfo.setShopName(itemShopNameList.get(i).trim());
//
//					resultList.add(kakakuItemInfo);
//				}

			}
		} catch (MalformedURLException e) {
			throw new KakakuException(e);
		} catch (IOException e) {
			throw new KakakuException(e);
		} catch (ParseException e) {
			throw new KakakuException(e);
		} finally {
			if (bufferedReader != null) {
				try {
					bufferedReader.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			if (connection != null) {
				connection.disconnect();
			}
		}

		return resultList;
	}

	public File getCsvFile() throws KakakuException {
		OutputStreamWriter out = null;
		BufferedReader bufferedReader = null;
		HttpURLConnection connection1 = null;
		OutputStreamWriter outCsv = null;
		HttpURLConnection connectionCsv = null;
		BufferedReader bufferedReaderCsv = null;
		File csvFile = null;
		try {
			String KAKAKU_DOWNLOAD_CVS = ResourceUtil.getProperties(
					"yakaten.properties")
					.getProperty("kakaku.download.cvs.url");
			URL loginUrl = new URL(KAKAKU_DOWNLOAD_CVS);

			connection1 = (HttpURLConnection) loginUrl.openConnection();
			connection1.connect();

			InputStream urlStream = connection1.getInputStream();
			bufferedReader = new BufferedReader(new InputStreamReader(
					urlStream, "shift_jis"));
			String ss = null;
			StringBuffer total = new StringBuffer();
			while ((ss = bufferedReader.readLine()) != null) {
				total.append(ss);
			}

			if (logger.isDebugEnabled()) {
				logger.debug(total);
			}

			Matcher matcherForm1 = PATTERN_HOTTID.matcher(total);
			if (matcherForm1.find()) {
				String hottid = matcherForm1.group(1);
				connectionCsv = (HttpURLConnection) loginUrl.openConnection();
				connectionCsv.setDoOutput(true);
				outCsv = new OutputStreamWriter(
						connectionCsv.getOutputStream(), "shift_jis");
				outCsv.write("HidDownloadType=" + 2 + "&hottid=" + hottid);
				outCsv.flush();

				InputStream urlStreamCsv = connectionCsv.getInputStream();
				String fileName = connectionCsv
						.getHeaderField("Content-Disposition");
				fileName = fileName.substring(fileName.indexOf("=") + 1);
				bufferedReaderCsv = new BufferedReader(new InputStreamReader(
						urlStreamCsv, "shift_jis"));
				String ssCsv = null;
				StringBuffer totalCsv = new StringBuffer();
				while ((ssCsv = bufferedReaderCsv.readLine()) != null) {
					totalCsv.append(ssCsv + "\r\n");
				}
				String folder = ResourceUtil
						.getProperties("yakaten.properties").getProperty(
								"kakaku.csv.folder");
				csvFile = new File(folder + fileName + ".bak");
				IOUtils.write(totalCsv, new FileOutputStream(csvFile),
						"shift_jis");
			}
		} catch (MalformedURLException e) {
			throw new KakakuException(e);
		} catch (IOException e) {
			throw new KakakuException(e);
		} finally {
			if (out != null) {
				try {
					out.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}

			if (outCsv != null) {
				try {
					outCsv.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			if (bufferedReader != null) {
				try {
					bufferedReader.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}

			if (bufferedReaderCsv != null) {
				try {
					bufferedReaderCsv.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			if (connection1 != null) {
				connection1.disconnect();
			}

			if (connectionCsv != null) {
				connectionCsv.disconnect();
			}
		}

		return csvFile;

	}

	public List <String> getCsvFileData() throws KakakuException {
		OutputStreamWriter out = null;
		BufferedReader bufferedReader = null;
		HttpURLConnection connection1 = null;
		OutputStreamWriter outCsv = null;
		HttpURLConnection connectionCsv = null;
		BufferedReader bufferedReaderCsv = null;
		List <String> csvFileData = new ArrayList<String>();
		try {
			String KAKAKU_DOWNLOAD_CVS = ResourceUtil.getProperties(
					"yakaten.properties")
					.getProperty("kakaku.download.cvs.url");
			URL loginUrl = new URL(KAKAKU_DOWNLOAD_CVS);

			connection1 = (HttpURLConnection) loginUrl.openConnection();
			connection1.connect();

			InputStream urlStream = connection1.getInputStream();
			bufferedReader = new BufferedReader(new InputStreamReader(
					urlStream, "shift_jis"));
			String ss = null;
			StringBuffer total = new StringBuffer();
			while ((ss = bufferedReader.readLine()) != null) {
				total.append(ss);
			}

			if (logger.isDebugEnabled()) {
				logger.debug(total);
			}

			Matcher matcherForm1 = PATTERN_HOTTID.matcher(total);
			if (matcherForm1.find()) {
				String hottid = matcherForm1.group(1);
				connectionCsv = (HttpURLConnection) loginUrl.openConnection();
				connectionCsv.setDoOutput(true);
				outCsv = new OutputStreamWriter(
						connectionCsv.getOutputStream(), "shift_jis");
				outCsv.write("HidDownloadType=" + 2 + "&hottid=" + hottid);
				outCsv.flush();

				InputStream urlStreamCsv = connectionCsv.getInputStream();
				String fileName = connectionCsv
						.getHeaderField("Content-Disposition");
				fileName = fileName.substring(fileName.indexOf("=") + 1);
				bufferedReaderCsv = new BufferedReader(new InputStreamReader(
						urlStreamCsv, "shift_jis"));
				String ssCsv = null;
				while ((ssCsv = bufferedReaderCsv.readLine()) != null) {
					csvFileData.add(ssCsv);
				}
			}
		} catch (MalformedURLException e) {
			throw new KakakuException(e);
		} catch (IOException e) {
			throw new KakakuException(e);
		} finally {
			if (out != null) {
				try {
					out.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}

			if (outCsv != null) {
				try {
					outCsv.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			if (bufferedReader != null) {
				try {
					bufferedReader.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}

			if (bufferedReaderCsv != null) {
				try {
					bufferedReaderCsv.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			if (connection1 != null) {
				connection1.disconnect();
			}

			if (connectionCsv != null) {
				connectionCsv.disconnect();
			}
		}

		return csvFileData;

	}

	public boolean uploadCsvFile(File csvFile) throws KakakuException {
		OutputStreamWriter out = null;
		BufferedReader bufferedReader = null;
		HttpURLConnection connection1 = null;
		OutputStreamWriter outCsv = null;
		HttpURLConnection connectionCsv = null;
		BufferedReader bufferedReaderCsv = null;
		InputStreamReader ir = null;
		BufferedReader br = null;
		boolean result = false;
		try {
			String KAKAKU_UPLOAD_CVS = ResourceUtil.getProperties(
					"yakaten.properties").getProperty("kakaku.upload.cvs.url");
			URL loginUrl = new URL(KAKAKU_UPLOAD_CVS);

			connection1 = (HttpURLConnection) loginUrl.openConnection();
			connection1.connect();

			InputStream urlStream = connection1.getInputStream();
			bufferedReader = new BufferedReader(new InputStreamReader(
					urlStream, "shift_jis"));
			String ss = null;
			StringBuffer total = new StringBuffer();
			while ((ss = bufferedReader.readLine()) != null) {
				total.append(ss);
			}
			if (logger.isDebugEnabled()) {
				logger.debug(total);
			}
			Matcher matcherForm1 = PATTERN_HOTTID.matcher(total);
			if (matcherForm1.find()) {
				String hottid = matcherForm1.group(1);
				connectionCsv = (HttpURLConnection) loginUrl.openConnection();
				connectionCsv.setDoOutput(true);
				String BOUNDARYSTR = "---------------------------11694269024691";
				String BOUNDARY = "--" + BOUNDARYSTR + "\r\n";
				String BOUNDARYEND = "--" + BOUNDARYSTR + "--\r\n";

				connectionCsv.setRequestProperty("Content-type",
						"multipart/form-data;boundary=" + BOUNDARYSTR);

				String mail = ResourceUtil.getProperties("yakaten.properties")
						.getProperty("kakaku.update.mail");
				StringBuffer sb = new StringBuffer();
				sb.append(BOUNDARY);
				sb
						.append("Content-Disposition: form-data; name=\"TxtMailAddress\"");
				sb.append("\r\n\r\n");
				sb.append(mail);
				sb.append("\r\n");

				sb.append(BOUNDARY);
				sb.append("Content-Disposition: form-data; name=\"hreg\"");
				sb.append("\r\n\r\n");
				sb.append("1");
				sb.append("\r\n");

				sb.append(BOUNDARY);
				sb.append("Content-Disposition: form-data; name=\"hottid\"");
				sb.append("\r\n\r\n");
				sb.append(hottid);
				sb.append("\r\n");

				sb.append(BOUNDARY);
				sb
						.append("Content-Disposition: form-data; name=\"TxtCSVFile\"; filename=\""
								+ csvFile.getName() + "\"");
				sb.append("\r\n");
				sb.append("Content-Type: application/vnd.ms-excel");
				sb.append("\r\n\r\n");

				ir = new InputStreamReader(new FileInputStream(csvFile),
						"shift_jis");
				br = new BufferedReader(ir);
				String current = "";
				while ((current = br.readLine()) != null) {
					sb.append(current + "\r\n");
				}

				sb.append(BOUNDARYEND);

				outCsv = new OutputStreamWriter(
						connectionCsv.getOutputStream(), "shift_jis");

				outCsv.write(sb.toString());
				outCsv.flush();

				InputStream urlStreamCsv = connectionCsv.getInputStream();
				bufferedReaderCsv = new BufferedReader(new InputStreamReader(
						urlStreamCsv, "shift_jis"));
				String ssCsv = null;
				StringBuffer totalCsv = new StringBuffer();
				while ((ssCsv = bufferedReaderCsv.readLine()) != null) {
					totalCsv.append(ssCsv);
				}
				if (logger.isDebugEnabled()) {
					logger.debug(total);
				}
				if (totalCsv.indexOf("アップロード完了") > -1) {
					result = true;
				}

			}
		} catch (MalformedURLException e) {
			throw new KakakuException(e);
		} catch (IOException e) {
			throw new KakakuException(e);
		} finally {
			if (out != null) {
				try {
					out.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}

			if (outCsv != null) {
				try {
					outCsv.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			if (bufferedReader != null) {
				try {
					bufferedReader.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}

			if (bufferedReaderCsv != null) {
				try {
					bufferedReaderCsv.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			if (connection1 != null) {
				connection1.disconnect();
			}

			if (connectionCsv != null) {
				connectionCsv.disconnect();
			}

			if (br != null) {
				try {
					br.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		return result;
	}

	public boolean uploadCsvConfirm() throws KakakuException {
		OutputStreamWriter out = null;
		BufferedReader bufferedReader = null;
		HttpURLConnection connection1 = null;
		OutputStreamWriter outCsv = null;
		HttpURLConnection connectionCsv = null;
		BufferedReader bufferedReaderCsv = null;
		boolean result = false;
		try {
			String KAKAKU_UPLOAD_CONFIRM = ResourceUtil.getProperties(
					"yakaten.properties").getProperty(
					"kakaku.upload.confirm.url");
			URL loginUrl = new URL(KAKAKU_UPLOAD_CONFIRM);

			connection1 = (HttpURLConnection) loginUrl.openConnection();
			connection1.connect();

			InputStream urlStream = connection1.getInputStream();
			bufferedReader = new BufferedReader(new InputStreamReader(
					urlStream, "shift_jis"));
			String ss = null;
			StringBuffer total = new StringBuffer();
			while ((ss = bufferedReader.readLine()) != null) {
				total.append(ss);
			}
			if (logger.isDebugEnabled()) {
				logger.debug(total);
			}
			Matcher matcherForm1 = PATTERN_HOTTID.matcher(total);
			if (matcherForm1.find()) {
				String hottid = matcherForm1.group(1);
				connectionCsv = (HttpURLConnection) loginUrl.openConnection();
				connectionCsv.setDoOutput(true);
				outCsv = new OutputStreamWriter(
						connectionCsv.getOutputStream(), "shift_jis");
				String mail = ResourceUtil.getProperties("yakaten.properties")
						.getProperty("kakaku.update.mail");
				outCsv.write("hreg=1&TxtMailAddress=" + mail + "&hottid="
						+ hottid);
				outCsv.flush();

				InputStream urlStreamCsv = connectionCsv.getInputStream();
				bufferedReaderCsv = new BufferedReader(new InputStreamReader(
						urlStreamCsv, "shift_jis"));
				String ssCsv = null;
				StringBuffer totalCsv = new StringBuffer();
				while ((ssCsv = bufferedReaderCsv.readLine()) != null) {
					totalCsv.append(ssCsv);
				}
				if (logger.isDebugEnabled()) {
					logger.debug(total);
				}
				if (totalCsv.indexOf("処理開始") > -1) {
					result = true;
				}
			}
		} catch (MalformedURLException e) {
			throw new KakakuException(e);
		} catch (IOException e) {
			throw new KakakuException(e);
		} finally {
			if (out != null) {
				try {
					out.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}

			if (outCsv != null) {
				try {
					outCsv.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			if (bufferedReader != null) {
				try {
					bufferedReader.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}

			if (bufferedReaderCsv != null) {
				try {
					bufferedReaderCsv.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			if (connection1 != null) {
				connection1.disconnect();
			}

			if (connectionCsv != null) {
				connectionCsv.disconnect();
			}
		}
		return result;
	}

	public static void main(String[] args) {
		try {
			System.getProperties().put("proxySet", "true");

			System.getProperties().put("proxyPort", "80");

			System.getProperties().put("proxyHost", "proxysv");
			// System.out.println(KakakuService.getItemInfo("K0000339848"));
			KakakuItemService service = new KakakuItemService();
			// KakakuLogin login = new KakakuLogin();
			// login.doLogin("tydkenms", "38srka2b");
			// File csvFile= service.getCsvFile();
			// logger.debug(csvFile.exists());
			// logger.debug(service.uploadCsvFile(new
			// File("c:/kakaku/20120722141925-2179.csv")));
			List<KakakuItemInfoDto> resultList = service
					.getItemInfo("K0000587980");
			//K0000271941
			for (KakakuItemInfoDto current : resultList) {
				System.out.println(current);
			}

		} catch (KakakuException e) {
			e.printStackTrace();
		}

	}
}
